#!/usr/bin/perl -w
use strict;

open F, "<p02-input.txt" or die;
my $line;
my $city;
my $temp;
my @goodlines;
my $n = 0;
my $totaltemp = 0;

while ($line = <F>) {
    $line =~ s/^\s*//;
    $line =~ s/\s*$//;
    $line =~ s/\s+/ /g;
    $line =~ tr/a-z/A-Z/;
    if ($line eq 'QUIT') {
        last;
    }
    elsif ($line =~ /^([A-Z ]+) (-?\d+)$/) {
        # we are good, formatting wise
        $city = $1;
        $temp = $2;
        if ((-99 <= $temp) && ($temp <= 99)) {
            # Now we are really good
            $n++;
            $totaltemp += $temp;
            push @goodlines, "$city $temp";
        }
    }
    else {
        # not good
        print "    Bad line. Try again. :  \"$line\"\n";
    }
}
close F;

for (@goodlines) {
    print "$_\n";
}
print "\nCities: $n\n";
print "Average Temperature: " . $totaltemp / $n . "\n";

